import { ElNotification } from 'element-plus';
import { Login, Register} from "~/utils/api";
import { useRouter } from 'vue-router';

const toLogin = ref()
const toAdmin = ref(false)
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const passwordPattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+[\]{};':"\\|,.<>?]).{8,}$/;
export const useAuth = () => {
    const router = useRouter();

    const handleSubmit = async (email: string, password: string, isLogin: boolean) => {
        const userCredentials = {
            email,
            password
        }
        if (isLogin) {
            try {
                await Login(userCredentials).then((res) => {
                    if (res.value.email === userCredentials.email) {
                        const setStorage = {
                            user_id: res.value.user_id,
                            email: res.value.email,
                            password: res.value.password,
                            "x-access-token": res.value.access_token
                        };
                        localStorage.setItem('star-bucket-info', JSON.stringify(setStorage));
                    }
                    ElNotification({
                        title: 'Login',
                        message: '账号登录成功！',
                        type: 'success',
                        duration: 1000
                    });
                    toAdmin.value = true
                    // router.push('/about');
                }).catch((error) => {
                    console.log("error: ", error)
                })

            } catch (error) {
                console.log("error: ", error)
            }
        } else {
            if (!isLogin && password) {
                if(!emailPattern.test(email) || !passwordPattern.test(password)) {
                    ElNotification({
                        title: '格式验证',
                        message: '邮箱或者密码格式不对！',
                        type: 'warning',
                        duration: 1000
                    });
                    toLogin.value = isLogin;
                    return
                }
                try {
                    await Register(userCredentials).then((res) => {
                        ElNotification({
                            title: 'Register',
                            message: '账号创建成功！',
                            type: 'success',
                            duration: 1000
                        });
                        toLogin.value = true;

                    }).catch((error) => {
                        toLogin.value = false;
                        console.log("error: ", error)
                    })

                } catch (error) {
                    console.log("error: ", error);
                }
            }

        }
    };

    return {
        handleSubmit,
        toLogin,
        toAdmin
    };
};
